/**
 * @class ExtGames.Stack
 * @param {Array} An ordered array of cards to initialise this stack with
 * Represents an ordered stack of cards
 */
ExtGames.PlayArea = function(config) {
  var config = config || {};
  
  this.type = config.type;
  this.opp = config.opp || 0;
  this.savedItems = [];
    
  ExtGames.PlayArea.superclass.constructor.call(this, config);
    
  this.addEvents(
    /**
     * @event carddropped
     * Fires when a card is dropped on this stack
     * @param {ExtGames.Stack} this The stack the card was dropped on
     * @param {ExtGames.Card} card The card that was dropped
     */
    'carddropped'
  );
  
  this.on('render',      this.initializeDropTarget, this);
  this.on('afterlayout', this.applyClasses,         this);
};

Ext.extend(ExtGames.PlayArea, ExtGames.CardHolder, {
	
   type: 0,
   
   opp: 0,
   
   savedItems: [],
   
   replaceJokers: false,
	
	
  /**
   * Returns true if the request drop is allowed
   * @param {ExtGames.Card} cardToDrop The card the user wishes to drop onto this stack
   * @return {Boolean} True if this drop is allowed
   */
  dropAllowed: function(cardToDrop) {
	  if (cardToDrop.location.itemId != 'hand' && cardToDrop.location != this) {
		  return false;
	  }
	  
	  
	  return true;
	  
	  if (this.items && this.items.items && this.items.items.length > 0) {
	  	var firstCard = this.items.items[0];
	  	var lastCard = this.items.items[this.items.items.length-1];
	  	
	  	
	  }
	  
  },
  
  
  /**
   * Iterates over the cards in this stack, adding CSS classes accordingly.
   * Intended to be attached to the afterlayout event
   */
  applyClasses: function() {
	  	  
    this.items.each(function(c) {
      if (c == this.items.items[this.items.length - 1]) {
        //top card in stack
        c.addClass('x-solitaire-card-right');
        c.removeClass('x-solitaire-card-left');
        c.reveal();
      } else {
        c.addClass('x-solitaire-card-left');
        c.removeClass('x-solitaire-card-right');
      };
      
      c.initializeDragSource();
    }, this);
  },
  
  /**
   * Creates the markup to render this stack
   */
  onRender: function(ct, position) {
	  	  
	var label = 'Group';
	if (this.itemId.indexOf('run') > 0) {
		label = 'Run';
	}
	  
	var children = [];
	if (this.opp == 0) {
		children = [
		           {
		           	tag: 'h1',
		           	html: label
		           },
		           {
		             cls:   'x-solitaire-play x-solitaire-play-my',
		             style: 'background: url('+cardUrl+') no-repeat bottom left;'
		           }
		         ];
		
		this.el = ct.createChild({
		      cls: 'x-solitaire-hand-wrapper',
		      style: 'min-width: 72px;',
		      children: children
		    });
	}
	else {
		children = [
           {
             cls:   'x-solitaire-play x-solitaire-play-opp',
             style: 'background: url('+cardUrl+') no-repeat bottom left;'
           }
         ];
		
		this.el = ct.createChild({
		      cls: 'x-solitaire-hand-wrapper',
		      //style: 'min-width: 72px;',
		      children: children
		    });
	}
	
    
    this.stackHolder = this.el.child('.x-solitaire-play');
    
    ExtGames.PlayArea.superclass.onRender.apply(this, arguments);
  },

  getLayoutTarget: function(){
    return this.stackHolder;
  },
  
  /**
   * Sets up a drag zone to allow the top card of each stack to be draggable
   */
  
  didPlay: function() {
	  if (this.items && this.items.items && this.items.items.length > 0) {
		  return true;
	  }
	  return false;
  },
  
  validRun: function(numCards) {
  	  var items = this.items.items.slice(0);
	  //items = items.sort(sortCards);
	  
	  if (items.length < numCards) {
		  return false;
	  }
	  
	  while (items.length > 0 && items[0].joker == true) {
		  items.shift();
	  }
	  
	 if (items.length == 0) {
	  	// All Jokers
	  	return true;
	  }
	  
	  var firstNum = items[0].numbers.indexOf(items[0].number);
      var firstSuit = items[0].suit;
	  
	  for (var i = 1; i < items.length; i++) {
		  firstNum = (firstNum+1)%items[i].numbers.length;
	  	  if (items[i].joker != true) {
			  if (items[i].suit != firstSuit) {
				  return false;
			  }
			  var nextNum = items[i].numbers.indexOf(items[i].number);
			  if (nextNum != (firstNum)) {
				  return false;
			  }
		  }
	  }
	  return true;
  },
  
  validGroup: function(numCards) {
  	  var items = this.items.items;
	  if (items.length < numCards) {
		  return false;
	  }
	 
	  while (items.length > 0 && items[0].joker == true) {
		  items.shift();
	  }
	  
	 if (items.length == 0) {
	  	// All Jokers
	  	return true;
	  }
	 
	  var firstNum = items[0].number;
	  for (var i = 1; i < items.length; i++) {
	  	  if (items[i].joker != true) {
			  var nextNum = items[i].number;
			  if (nextNum != firstNum) {
				  return false;
			  }
		  }
	  }
	  return true;
  },
  
  saveCards: function() {
	  if (this.items && this.items.items) {
		  
		  for (var i = 0; i < this.items.items.length; i++) {
		  	  if (this.type == 0 && this.items.items[i].joker == true) {
		  	  	//continue;
		  	  }
			  this.savedItems.push(this.items.items[i]);
		  }
		  
		  console.log("Saved: "+JSON.stringify(this.toObject()));
		  
	  }
  },
  
  isSaved: function(card) {
	if (this.savedItems) {
		for (var i = 0; i < this.savedItems.length; i++) {
			if (this.savedItems[i] === card) {
				return true;
		  	}
		}
	}
	return false;
  },
  
  toObject: function() {
	  var o = {};
	  o.type = this.type;
	  o.cards = [];
	  
	  if (this.items && this.items.items) {
		  for (var i = 0; i < this.items.items.length; i++) {
			  var c = this.items.items[i];
			  o.cards[i] = c.toObject();
		  }
	  }
	  
	  return o;
  },
  
  getNewCardsObject: function() {
	  var o = {};
	  o.type = this.type;
	  o.cards = [];
	  
	  if (this.items && this.items.items) {
		  for (var i = 0; i < this.items.items.length; i++) {
			  var c = this.items.items[i];
			  if (this.savedItems.indexOf(c) < 0) {
				  var cardO = c.toObject();
				  cardO.pos = i;
				  o.cards.push(cardO);
			  }
		  }
	  }
	  
	  return o;
  },
  
  rearrange: function(card, e) {
  	  if (this.isSaved(card)) {
  	  	return;
  	  }
  	
	  var pixelOffset = 20;
	  
	  var x = e.getXY()[0];
	  var y = e.getXY()[1];
	  
	  var items = this.items.items;
	  for (var i = 0; i < items.length; i++) {
		  var newX = items[i].getEl().getXY()[0];
		  if ((x - newX) <= pixelOffset && (x - newX) >= 0) {
			  card.move(this, i);
			  return;
		  } 
	  }
	  card.move(this);
  },
  
  replaceJoker: function(card) {
  	
  }
  
});